package com.ang.juc.n6;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.stream.IntStream;

@Slf4j
public class Test2 {

    public static void main(String[] args) throws InterruptedException {
//        AccountOpt opt = new AccountOpt(0);
//        //2个共享对象，账户
//        AccountOpt account1 = new AccountOpt(10000);
//        AccountOpt account2 = new AccountOpt(10000);

        AccountOpt2 opt = new AccountOpt2(0);
        //2个共享对象，账户
        AccountOpt2 account1 = new AccountOpt2(10000);
        AccountOpt2 account2 = new AccountOpt2(10000);

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                opt.transfer(account1, account2, 100);
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                opt.transfer(account2, account1, 100);
            }
        });

        t1.start();
        t2.start();

        //线程跑完，在统计
        t1.join();
        t2.join();

        System.out.println("账户总额：" + (account1.getMoney()+account2.getMoney()));
    }


    @Data
    static class AccountOpt{
        private Integer money;

        public AccountOpt(Integer money){
            this.money = money;
        }

        //转账
        public void transfer(AccountOpt source, AccountOpt target, Integer money){
            if(source.getMoney() > 0){
                source.setMoney(source.getMoney() - money);
                target.setMoney(target.getMoney() + money);
            }
        }
    }

    @Data
    static class AccountOpt2{
        private Integer money;

        public AccountOpt2(Integer money){
            this.money = money;
        }

        //转账
        public void transfer(AccountOpt2 source, AccountOpt2 target, Integer money){
            synchronized (this) {
                if (source.getMoney() > 0) {
                    source.setMoney(source.getMoney() - money);
                    target.setMoney(target.getMoney() + money);
                }
            }
        }
    }
}
